<template>
  <div class="content">
    <!--头部-->
    <div class="header-setting" :style="expendStyle">
      <a-breadcrumb class="breadcrumb">
        <a-breadcrumb-item>
          <a href="../main">首页</a>
        </a-breadcrumb-item>
        <a-breadcrumb-item>收费管理</a-breadcrumb-item>
        <a-breadcrumb-item>修改订单</a-breadcrumb-item>
      </a-breadcrumb>

      <!--查询条件-->
      <div class="box-condition-body">
        <!--
                &lt;!&ndash; 选项 &ndash;&gt;
                <div id="tableControl" style="display: flex; margin: 0 50px">
                  <div id="view-select-0" class="left-radius-7" v-on:click="orderTypeTableSwtch(0)">全部订单</div>
                  <div id="view-unselect-0" v-on:click="orderTypeTableSwtch(1)">当月订单</div>
                  <div id="view-unselect-0" class="right-radius-7" v-on:click="orderTypeTableSwtch(2)">跨月订单</div>
                </div>
-->

        <div class="box-condition-item">
          <div style="margin: 0 50px">时间过滤类型</div>
          <a-button type="primary" style="margin: 0 0 0 20px" @click="timeTypeChange(0)"
            >按进场时间</a-button
          >
          <a-button type="primary" style="margin: 0 0 0 20px" @click="timeTypeChange(1)"
            >按离场时间</a-button
          >
          <a-button type="primary" style="margin: 0 0 0 20px" @click="timeTypeChange(2)"
            >按订单时间</a-button
          >
          <div style="margin: 0 50px">{{ timeTypeStr }}时间</div>
          <template>
            <div class="button_time">
              <a-button type="primary" @click="button_time(0)" :style="computedStyle(0)"
                >今天</a-button
              >
              <a-button type="primary" @click="button_time(1)" :style="computedStyle(1)"
                >昨天</a-button
              >
              <a-button type="primary" @click="button_time(2)" :style="computedStyle(2)"
                >本周</a-button
              >
              <a-button type="primary" @click="button_time(3)" :style="computedStyle(3)"
                >上周</a-button
              >
              <a-button type="primary" @click="button_time(4)" :style="computedStyle(4)"
                >本月</a-button
              >
              <a-button type="primary" @click="button_time(5)" :style="computedStyle(5)"
                >上月</a-button
              >
            </div>
          </template>
          <template>
            <div style="margin: auto 50px">
              <a-range-picker
                :showTime="{ format: 'HH:mm' }"
                format="YYYY-MM-DD HH:mm"
                :placeholder="['开始时间', '结束时间']"
                @ok="onOk"
                @change="onChange"
                :value="rangePicker()"
              />
            </div>
          </template>
        </div>
        <div class="box-condition-item">
          <div style="margin: 0px 10px 0px 50px">停车点</div>
          <template>
            <a-select
              style="margin: 0 100px 0 16px; width: 200px"
              showSearch
              mode="multiple"
              placeholder="选择停车点"
              optionFilterProp="children"
              v-model="selectParkId"
              @change="selectParkChange"
              :allowClear="true"
            >
              <a-select-option v-for="p in parks" :key="p.id" :value="p.id"
                >{{ p.parkName }}
              </a-select-option>
            </a-select>
          </template>
          <div style="margin: 0px 10px 0px 50px">停车位编号</div>
          <template>
            <a-input
              style="margin: 0px 20px 0 0px; width: 200px"
              v-model="inputTruckSpaceName"
              placeholder="停车位编号"
            />
          </template>
          <div style="margin: 0px 10px 0px 50px">系统订单号</div>
          <template>
            <a-input
              style="margin: 0px 20px 0 0px; width: 200px"
              v-model="inputUorder"
              placeholder="系统订单号"
            />
          </template>
          <div style="margin: 0px 10px 0px 50px">交易订单号</div>
          <template>
            <a-input
              style="margin: 0px 20px 0 0px; width: 200px"
              v-model="inputTorder"
              placeholder="交易订单号"
            />
          </template>
        </div>
        <div class="box-condition-item">
          <div style="margin: 0px 10px 0px 50px">设备编号</div>
          <template>
            <a-input
              style="margin: 0 100px 0 0px; width: 200px"
              v-model="inputImei"
              placeholder="设备编号"
            />
          </template>
          <div style="margin: 0px 40px 0px 50px">车牌号</div>
          <template>
            <a-input
              style="margin: 0 100px 0 0px; width: 200px"
              v-model="inputPlate"
              placeholder="车牌号"
            />
          </template>
          <div style="margin: 0 10px">缴费状态</div>
          <a-button type="primary" style="margin: 0 0 0 20px" @click="plateScreen(1)"
            >未交费</a-button
          >
          <a-button type="primary" style="margin: 0 0 0 20px" @click="plateScreen(2)"
            >已缴费</a-button
          >
          <a-button type="primary" style="margin: 0 0 0 20px" @click="plateScreen(3)"
            >计费中</a-button
          >
          <a-button type="primary" style="margin: 0 0 0 20px" @click="plateScreen(4)"
            >已退款</a-button
          >

          <!-- 清除 -->
          <div style="margin: 0 50px">
            <a-button icon="search" type="primary" style="margin: 0 0 0 20px" @click="queryData">查询</a-button>
            <a-button icon="sync" style="margin: 0 0 0 20px" @click="reset">重置</a-button>
          </div>
        </div>
        <div class="box-expand" @click="switchExpend">
          点击{{ isExpand ? "收起" : "展开" }}
        </div>
      </div>
    </div>

    <!-- 表单 -->
    <div class="box-form">
      <!--工具栏-->
      <div class="box-tool">
        <div></div>
        <div style="display: flex">
          总合计【 应收:{{ this.should }}元 &emsp;实收:{{ this.reality }}元
          优惠:{{ this.favorableAmount }}元】 &emsp;
          <a-button type="primary" @click="visible = true">添加</a-button>
          &nbsp;
          <a-button type="primary" @click="exportExcel" icon="download">导出记录</a-button>
        </div>
      </div>
      <!--数据表格-->
      <div class="box-table">
        <a-table
          :columns="columns"
          :dataSource="dataSource"
          :pagination="pagination"
          @change="tableChange"
          bordered
          size="small"
          :scroll="scroll"
          :customRow="customRow"
          :rowClassName="setRowClassName"
        >
          <template slot="shouldMoneySlot" slot-scope="text">
            <div>{{ text == undefined || text == "" ? text : text / 100 }}</div>
          </template>
          <template slot="realityMoneySlot" slot-scope="text">
            <div>{{ text == undefined || text == "" ? 0 : text / 100 }}</div>
          </template>
          <template slot="favorableAmountSlot" slot-scope="text">
            <div>{{ text == undefined || text == "" ? 0 : text / 100 }}</div>
          </template>
          <template slot="invoicesStatus" slot-scope="text">
            <div>{{ text == 1 ? "已开票" : "未开票" }}</div>
          </template>
          <template slot="payStatusSlot" slot-scope="text">
            <!--                      支付状态 1：等待 2：成功 3：取消 4：失败 5：支付进行中-->
            <span v-if="text == 1">等待</span>
            <span v-if="text == 2">成功</span>
            <span v-if="text == 3">取消</span>
            <span v-if="text == 4">失败</span>
            <span v-if="text == 5">支付中</span>
            <span v-if="text == 6">已退款</span>
          </template>

          <template slot="refundTypeSlot" slot-scope="text, record">
            <!--  退款类型0：未退款 1：当月 2：跨月-->
            <span v-if="text == 1">当天退款</span>
            <span v-if="text == 2"
              ><a v-on:click="refundRecordWindows(record.wid)"
                >跨天退款</a
              ></span
            >
          </template>

          <template slot="pdf" slot-scope="text">
            <div v-if="text != '' && text != undefined">
              <a :href="text" target="_Blank">发票预览</a>
            </div>
          </template>
          <!-- 操作项 -->
          <!-- 插槽 opertion -->
          <!-- 带数据插槽 text | record | index -->
          <template slot="operation1" slot-scope="text, record">
            <div class="editable-row-operations">
              <!-- 当月未支付或免费订单、未结束订单才能作废 -->
              <span v-if="
                  (record.payStatus != 2 || record.shouldMoney == 0) &&
                  ((new Date().getFullYear() == new Date(record.endTime).getFullYear() &&
                    new Date().getMonth() == new Date(record.endTime).getMonth()) ||
                    record.endTime == null || record.endTime == '' || record.endTime == undefined)" >
                <!-- key: "0" || record => object || text => object || index: 0 -->
                <a-popconfirm
                  title="确认作废？"
                  okText="确认"
                  cancelText="取消"
                  @confirm="invalidOrder(record.id)"
                  placement="topLeft" >
                  <a>作废</a>&nbsp;|&nbsp;
                </a-popconfirm>
                <!-- <a v-on:click="updateMoneyWindows(record.wid, record.shouldMoney)">修改</a><br />&nbsp; -->
                <a-popconfirm
                  title="确认删除？"
                  okText="确认"
                  cancelText="取消"
                  @confirm="deleteOrder(record.id, record.wid)"
                  placement="topLeft">
                  <a>删除</a><br/>
                </a-popconfirm>
              </span>
              <span
                v-else-if=" (record.payStatus === 2 || record.payStatus === 6) &&
                  record.shouldMoney != '' && record.shouldMoney != '0' && record.shouldMoney != undefined && (record.realityMoney>0 || record.favorableAmount>0) ">
                <a v-on:click="refundWindows(record)">退款</a>
              </span>
              <span v-if="(record.endTime != null && record.endTime != undefined && record.endTime != ''  && (record.payStatus != 2 || record.shouldMoney == 0 ))">
                &nbsp;<a v-on:click="updateMoneyWindows(record.wid, record.shouldMoney,record.endTime)">修改</a>&nbsp;
              </span>
            </div>
          </template>

          <!--<template slot="detail"  slot-scope="text, record">
                        <a-button type="primary" @click="orderDetail(record)">订单详情</a-button>
                    </template> -->
          <!-- 脚步 -->
          <template slot="footer" v-if="dataSource.length != 0">
            <div style="display: flex; height: 30px; margin: 0 -16px">
              <div style="flex: 1 1 80%; height: 100%; padding-left: 1%">
                合计
              </div>
              <div style="flex: 1 0 6%; height: 100%; padding-left: 0.3%">
                {{ computedDue }}
              </div>
              <div style="flex: 1 0 5%; height: 100%; padding-left: 0.1%">
                {{ computedDueR }}
              </div>
              <div style="flex: 1 0 15%; height: 100%; padding-left: 0.1%">
                {{ computedDueF }}
              </div>
            </div>
          </template>
        </a-table>
      </div>
    </div>
    <!-- 修改订单弹窗 -->
    <a-modal
      title="修改订单"
      v-model="editOrderPopupData.visible"
      :confirmLoading="editOrderPopupData.loading"
      @cancel="
        () => {
          this.hideEditOrderPopupData();
        }
      "
      @ok="updateOrderMoney"
    >
      <a-row style="margin-top: 0.5em">
        <a-col :span="6">修改金额</a-col>
        <a-col :span="10">
          <a-input
            style="width: 70%"
            placeholder="修改金额(元)"
            v-model="money"
            type="text"
            onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
          />
          <a-input style="width: 70%" hidden v-model="wid" />
        </a-col>
      </a-row>
    </a-modal>

    <!-- 订单退款记录弹窗 -->
    <a-modal
      title="退款记录"
      v-model="refundRecordPopupData.visible"
      :confirmLoading="refundRecordPopupData.loading"
      @cancel="
        () => {
          this.hideRefundRecordPopupData();
        }
      "
    >
      <div class="box-table">
        <a-table
          :columns="refundRecordColumns"
          :dataSource="refundRecordDataSource"
          bordered
          size="small"
          :scroll="scroll"
          :rowClassName="setRowClassName"
        >
        </a-table>
      </div>
    </a-modal>

    <!-- 退款弹窗 -->
    <a-modal
      title="退款"
      v-model="refundPopupData.visible"
      :confirmLoading="refundPopupData.loading"
      @cancel="() => {this.hideRefundPopupData();}"
      @ok="refund">
      <a-input hidden v-model="wid" />
      <a-input hidden v-model="customerUserId" />
      <a-input hidden v-model="orderTime" />
      <a-row style="margin-top: 0.5em">
        <a-col :span="6">订单金额</a-col>
        <a-col :span="15">
          <a-input disabled v-model="money" type="text" />
        </a-col>
      </a-row>
      <a-row style="margin-top: 0.5em">
        <a-col :span="6">退款金额(元)</a-col>
        <a-col :span="15">
          <a-input
            placeholder="退款金额(元)"
            v-model="moneyNew"
            type="text"
            onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
          />
        </a-col>
      </a-row>
          <!-- v-if="
          new Date().getFullYear() != new Date(orderTime).getFullYear() ||
          new Date().getMonth() != new Date(orderTime).getMonth()" -->
      <span>
        <a-row style="margin-top: 0.5em">
          <a-col :span="6">退款备注</a-col>
          <a-col :span="15">
            <a-textarea
              maxlength="100"
              placeholder="退款备注"
              v-model="remark"
            />
          </a-col>
        </a-row>
      </span>
    </a-modal>

    <!-- 弹窗  @ok="handleOk" @cancel="cancel"-->
    <a-modal
      title="停车记录图片"
      v-model="correctPopupData.visible"
      :width="980"
      @cancel="cancelCorrect"
      :confirmLoading="correctPopupData.loading"
    >
      <div class="box-correction-popup">
        <!-- 图片 -->
        <a-carousel class="box-image" autoplay>
          <template v-for="image in correctPopupData.imageList">
            <img :key="image" :src="image" class="icon-image" />
          </template>
        </a-carousel>
      </div>
    </a-modal>
<!--    添加订单弹窗-->
    <model-add
      title="添加订单"
      :visible="visible"
      @handleOk="handleOk"
      @handleCancel="handleCancel"
    >
      <div class="viewBody">
        <div class="viewItem">
          <div class="itemText itemText1">订单完成时间</div>
          <div style="margin: 0 50px 0 0px; width: 200px">
            <a-date-picker @change="onChange" format="YYYY-MM-DD HH:mm:ss" />
          </div>
        </div>
        <div class="viewItem">
          <div class="itemText itemText1">本地订单号</div>
          <div style="margin: 0 50px 0 0px; width: 200px">
            <a-input placeholder="本地订单号" v-model="addOrder.localOrderNo" />
          </div>
        </div>
        <div class="viewItem">
          <div class="itemText itemText1">交易订单号</div>
          <div style="margin: 0 50px 0 0px; width: 200px">
            <a-input
              placeholder="交易订单号"
              v-model="addOrder.transactionOrderNo"
            />
          </div>
        </div>
        <div class="viewItem">
          <div class="itemText itemText1">应付金额(分)</div>
          <div style="margin: 0 50px 0 0px; width: 200px">
            <a-input
              placeholder="应付金额"
              onkeyup="value=value.replace(/[^\d]/g,'')"
              v-model.number="addOrder.payableMoney"
            />
          </div>
        </div>
        <div class="viewItem">
          <div class="itemText itemText1">应收金额(分)</div>
          <div style="margin: 0 50px 0 0px; width: 200px">
            <a-input
              placeholder="应收金额"
              onkeyup="value=value.replace(/[^\d]/g,'')"
              v-model.number="addOrder.shouldMoney"
            />
          </div>
        </div>
        <div class="viewItem">
          <div class="itemText itemText1">实收金额(分)</div>
          <div style="margin: 0 50px 0 0px; width: 200px">
            <a-input
              placeholder="实收金额"
              onkeyup="value=value.replace(/[^\d]/g,'')"
              v-model.number="addOrder.realityMoney"
            />
          </div>
        </div>
        <div class="viewItem">
          <div class="itemText itemText1">统一订单号</div>
          <div style="margin: 0 50px 0 0px; width: 200px">
            <a-input placeholder="统一订单号" v-model="addOrder.unifyOrderNo" />
          </div>
        </div>
        <div class="viewItem">
          <div class="itemText itemText1">优惠金额</div>
          <div style="margin: 0 50px 0 0px; width: 200px">
            <a-input
              placeholder="优惠金额"
              onkeyup="value=value.replace(/[^\d]/g,'')"
              v-model.number="addOrder.favorableAmount"
            />
          </div>
        </div>
      </div>
    </model-add>
  </div>
</template>

<script>
// import Constant from '../../utils/Constant';
import moment from "moment";
import CommonApi from "../../api/CommonApi";
import { Loading } from "element-ui";
import ParkingRecordApi from "../../api/charge/ChargeDetail";
import ModelAdd from "../../components/Modal/index.vue";
// import ThemeObservable from "@/observable/ThemeObservable";
// import mainApi from "@/api/MainApi";
const columns = [
  {
    title: "车牌号",
    dataIndex: "licencePlate",
    width: "6%",
  },
  {
    title: "进场时间",
    dataIndex: "startTime",
    width: "7%",
  },
  {
    title: "离场时间",
    dataIndex: "endTime",
    width: "7%",
  },
  {
    title: "订单完成时间",
    dataIndex: "orderTime",
    width: "7%",
  },
  {
    title: "停车点",
    dataIndex: "parkName",
    width: "8%",
  },
  {
    title: "停车位",
    dataIndex: "truckSpaceName",
    width: "5%",
  },
  {
    title: "设备编号",
    dataIndex: "imei",
    width: "11%",
  },
  {
    title: "支付方式",
    dataIndex: "pay",
    width: "5%",
  },
  {
    title: "订单状态",
    dataIndex: "payStatus",
    width: "5%",
    scopedSlots: { customRender: "payStatusSlot" },
  },
  {
    title: "系统订单号",
    dataIndex: "uorder",
    width: "10%",
  },
  {
    title: "交易订单号",
    dataIndex: "torder",
    width: "10%",
  },
  {
    title: "应收款（元）",
    dataIndex: "shouldMoney",
    scopedSlots: { customRender: "shouldMoneySlot" },
    width: "5%",
  },
  {
    title: "实收款（元）",
    dataIndex: "realityMoney",
    scopedSlots: { customRender: "realityMoneySlot" },
    width: "5%",
  },
  {
    title: "优惠（元）",
    dataIndex: "favorableAmount",
    scopedSlots: { customRender: "favorableAmountSlot" },
    width: "5%",
  },
  {
    title: "开票状态",
    dataIndex: "invoicesStatus",
    scopedSlots: { customRender: "invoicesStatus" },
    width: "5%",
  },
  {
    title: "发票",
    dataIndex: "pdf",
    scopedSlots: { customRender: "pdf" },
    width: "5%",
  },
  {
    title: "退款状态",
    dataIndex: "refundType",
    width: "5%",
    scopedSlots: { customRender: "refundTypeSlot" },
  },
  {
    title: "操作",
    scopedSlots: { customRender: "operation1" }, // 指定 template slot 名字
    width: "6%",
  },
];
const dataSource = [];

const refundRecordColumns = [
  {
    title: "退款时间",
    dataIndex: "createdTime",
    width: "7%",
  },
  {
    title: "退款方式",
    dataIndex: "type",
    customRender: function (text) {
      if (text == 1) {
        return "余额";
      } else {
        return "未知";
      }
    },
    width: "5%",
  },
  {
    title: "退款到用户",
    dataIndex: "userId",
    width: "11%",
  },
  {
    title: "退款金额（元）",
    dataIndex: "money",
    customRender: function (text) {
      if (text != undefined && text != null) {
        return text / 100;
      } else {
        return text;
      }
    },
    width: "6%",
  },
  {
    title: "备注",
    dataIndex: "remark",
    width: "11%",
  },
];
const refundRecordDataSource = [];

const queryCondition = {
  parkID: "",
  plate: "",
  torder: "",
  uorder: "",
  targetId: "",
  imei: "",
  truckSpaceName: "",
  startTimeStamp: "",
  endTimeStamp: "",
  timeScreenCondition: 6,
  payStatus: 0,
  limit: "10",
  curr: "1",
  timeType: 0,
  //多停点list
  pID: [],
};

const deleteOrderParam = {
  pid: "",
  wid: "",
};
const updateOrderParam = {
  pid: "",
  wid: "",
  money: "",
  type:""
};
const refundParam = {
  wid: "",
  type: "",
  money: "",
  remark: "",
  payType: "",
  userId: "",
};

export default {
  name: "ChargeDteil",

  /*数据层*/
  data() {
    return {
      isExpand: true,
      timeTypeStr: "按进场",
      parks: [],
      selectParkId: [],
      selectId: -1,
      momentArr: [],
      columns: columns,
      dataSource: dataSource,
      refundRecordColumns: refundRecordColumns,
      refundRecordDataSource: refundRecordDataSource,
      /*分页插件*/
      pagination: {
        showTotal: (total) => `共${total}条`,
        total: 0,
        current: 1,
        defaultCurrent: 1,
        showQuickJumper: true,
        defaultPageSize: 10,
      },
      /*表格固定头部*/
      scroll: {
        y: 550,
      },
      tableState: {
        rowId: -1,
      },
      /*当前选中的行数据*/
      currRowData: "",
      queryCondition,
      inputPlate: "",
      inputUorder: "",
      inputTorder: "",
      inputTruckSpaceName: "",
      inputImei: "",
      payStatus: 0,
      pay: "",

      /* 修改订单 */
      editOrderPopupData: {
        visible: false,
        loading: false,
        money: "",
        wid: "",
      },
      /* 退款记录 */
      refundRecordPopupData: {
        visible: false,
        loading: false,
      },
      /* 订单退款 */
      refundPopupData: {
        visible: false,
        loading: false,
        wid: "",
        money: "",
        type: "",
        userId: "",
        remark: "",
        payType: "",
        customerUserId: "",
      },
      /* 修正弹窗 */
      correctPopupData: {
        visible: false,
        loading: false,
        id: "",
        imageList: [],
      },
      time: "",
      should: 0,
      reality: 0,
      favorableAmount: 0,
      money: 0,
      moneyNew: 0,
      orderTime: "",
      remark: "",
      wid: "",
      customerUserId: "",
      payType: "",
      updatePay:"",
      updateType:1,
      type: "",
      userId: "",
      visible: false,
      addOrder: {
        orderTime: "",
        localOrderNo: "",
        transactionOrderNo: "",
        payableMoney: "",
        shouldMoney: "",
        realityMoney: "",
        unifyOrderNo: "",
        favorableAmount: "",
      },
    };
  },
  components: {
    ModelAdd,
  },

  /*方法层*/
  methods: {
    hideEditOrderPopupData() {
      this.editOrderPopupData.visible = false;
      this.wid = "";
      this.money = "";
    },
    hideRefundRecordPopupData() {
      this.refundRecordPopupData.visible = false;
      this.money = "";
      this.type = "";
      this.userId = "";
      this.remark = "";
      this.type = "";
      this.createTime = "";
    },
    hideRefundPopupData() {
      this.refundPopupData.visible = false;
      this.wid = "";
      this.money = "";
      this.type = "";
      this.userId = "";
      this.remark = "";
      this.payType = "";
      this.orderTime = "";
    },
    timeTypeChange(type) {
      if (type == 0) {
        this.timeTypeStr = "按进场";
      } else if (type == 1) {
        this.timeTypeStr = "按离场";
      } else if (type == 2) {
        this.timeTypeStr = "按订单";
      }
      this.queryCondition.timeType = 0;
      if (type != undefined) {
        this.queryCondition.timeType = type;
      }
      this.queryData();
    },
    /**表格**/
    tableChange(page) {
      this.queryCondition.curr = page.current;
      this.queryData();
      this.queryCondition.curr = 0;
    },
    /*时间按钮控制*/
    button_time(e) {
      this.selectId = e;
      let momentStart;
      let momentEnd;
      switch (e) {
        case 0:
          momentStart = moment().startOf("day");
          momentEnd = moment().endOf("day");
          break;
        case 1:
          momentStart = moment().add("day", -1).startOf("day");
          momentEnd = moment().add("day", -1).endOf("day");
          break;
        case 2:
          momentStart = moment().week(moment().week()).startOf("week");
          momentEnd = moment().week(moment().week()).endOf("week");
          break;

        case 3:
          momentStart = moment()
            .week(moment().week() - 1)
            .startOf("week");
          momentEnd = moment()
            .week(moment().week() - 1)
            .endOf("week");
          break;
        case 4:
          momentStart = moment().month(moment().month()).startOf("month");
          momentEnd = moment().month(moment().month()).endOf("month");
          break;
        case 5:
          momentStart = moment()
            .month(moment().month() - 1)
            .startOf("month");
          momentEnd = moment()
            .month(moment().month() - 1)
            .endOf("month");
          break;
        default:
          break;
      }
      this.momentArr[0] = momentStart;
      this.momentArr[1] = momentEnd;
      this.queryData();
    },

    rangePicker() {
      return this.momentArr;
    },

    plateScreen(sign) {
      this.queryCondition.payStatus = 0;
      if (sign != undefined) {
        this.queryCondition.payStatus = sign;
      }
      this.queryData();
    },

    reset() {
      this.inputPlate = "";
      this.inputTruckSpaceName = "";
      this.selectParkId = [];
      this.inputImei = "";
      this.inputUorder = "";
      this.inputTorder = "";
      this.momentArr = [];
      this.queryCondition.payStatus = 0;
      this.button_time(0);
    },

    getQueryCondition() {
      let condition = this.queryCondition;
      let startTimeStamp = "";
      let endTimeStamp = "";
      condition.plate = this.inputPlate;
      condition.truckSpaceName = this.inputTruckSpaceName;
      condition.pID = this.selectParkId || [];
      condition.imei = this.inputImei;
      condition.uorder = this.inputUorder;
      condition.torder = this.inputTorder;
      if(this.queryCondition.curr==0){
        this.queryCondition.curr==1;
      }
      // condition.payStatus=this.payStatus;
      if (this.momentArr != undefined && this.momentArr.length != 0) {
        condition.timeScreenCondition = "6";
        startTimeStamp = new Date(this.momentArr[0]).getTime() / 1000;
        endTimeStamp = new Date(this.momentArr[1]).getTime() / 1000;
      } else {
        condition.timeScreenCondition = "0";
      }
      condition.startTimeStamp = startTimeStamp;
      condition.endTimeStamp = endTimeStamp;
      return condition;
    },

    /* ---------------- 维度变化 -------------- */
    onChange(date) {
      this.selectId = -1;
      this.momentArr = date;
    },

    onOk() {
      this.selectId = -1;
      this.queryData();
    },

    selectParkChange() {
      this.queryData();
    },

    /* ---------------- 停车点 ---------------- */
    initParkList() {
      CommonApi.getParkList()
        .then((data) => {
          this.parks = data.data;
        })
        .catch((err) => {
          console.log("error:", err);
        });
    },

    /* ---------------- 删除订单操作 ---------------- */
    deleteOrder(pid, wid) {
      deleteOrderParam.pid = pid;
      deleteOrderParam.wid = wid;
      ParkingRecordApi.deleteOrder(deleteOrderParam)
        .then((data) => {
          let code = data.code;
          if (code === 2000) {
            this.$message.success("操作成功！");
            this.queryData();
          } else {
            this.$message.error("操作失败！" + data.data);
          }
        })
        .catch((error) => {
          console.log("删除订单数据异常！", error);
        });
    },
    /* ---------------- 作废订单 ---------------- */
    invalidOrder(pid) {
      if (pid == null || pid == "" || pid == undefined) {
        this.$message.warn("pid参数不能为空！");
        return;
      }
      //作废订单
      updateOrderParam.pid = pid;

      ParkingRecordApi.updateOrder(updateOrderParam)
        .then((data) => {
          let code = data.code;
          if (code === 2000) {
            this.$message.success("操作成功！");
            this.queryData();
          } else {
            this.$message.error("操作失败！" + data.data);
          }
        })
        .catch((error) => {
          console.log("操作异常！", error);
        });
    },
    /* ---------------- 弹出窗口 修改金额 ---------------- */
    updateMoneyWindows(wid, shouldMoney,endTime) {
      this.editOrderPopupData.visible = true;
      this.editOrderPopupData.loading = false;
      this.wid = wid;
      let sm = isNaN(parseInt(shouldMoney)) ? 0 : parseInt(shouldMoney) / 100;
      this.money = sm;
       if(((new Date().getFullYear() == new Date(endTime).getFullYear() &&
                    new Date().getMonth() == new Date(endTime).getMonth()) ||
                    endTime == null || endTime == '' || endTime == undefined)){
                      //当月
          this.updateType=1;
        }else{
          this.updateType=2;
        }
    },
    /* ---------------- 弹出窗口 退款记录详情列表 ---------------- */
    refundRecordWindows(wid) {
      this.refundRecordPopupData.visible = true;
      this.refundRecordPopupData.loading = false;
      const refundRecordParam = {
        wid: "",
      };
      refundRecordParam.wid = wid;
      ParkingRecordApi.refundRecordList(refundRecordParam)
        .then((data) => {
          let code = data.code;
          if (code === 2000) {
            this.refundRecordDataSource = data.data;
          } else {
            this.$message.error("操作失败！" + data.data);
          }
        })
        .catch((error) => {
          console.log("操作异常！", error);
          this.refundRecordPopupData.visible = false;
        });
    },
    /* ---------------- 弹出窗口 退款 ---------------- */
    refundWindows(record) {
      this.refundPopupData.visible = true;
      this.refundPopupData.loading = false;
      this.wid = record.wid;
      this.orderTime = record.orderTime;
      this.customerUserId = record.customerUserId;
      let sm = isNaN(parseInt(record.shouldMoney))
        ? 0
        : parseInt(record.shouldMoney) / 100;
      this.money = sm;
      this.updatePay=record.pay;
    },
    /* ---------------- 修改金额 ---------------- */
    updateOrderMoney() {
      let wid = this.wid;
      let money = this.money;
      if (wid == null || wid == "" || wid == undefined) {
        this.$message.warn("未产生费用记录或wid参数为空！");
        return;
      }
      if (!money && money !== 0) {
        this.$message.warn("money参数不能为空！");
        return;
      }
      //修改金额
      updateOrderParam.wid = wid;
      updateOrderParam.money = money * 100;
      updateOrderParam.type=this.updateType;
      this.editOrderPopupData.loading = true;
      ParkingRecordApi.updateOrder(updateOrderParam)
        .then((data) => {
          let code = data.code;
          if (code === 2000) {
            this.$message.success("操作成功！");
            this.hideEditOrderPopupData();
            this.queryData();
          } else {
            this.$message.error("操作失败！" + data.data);
          }
          this.editOrderPopupData.visible = false;
        })
        .catch((error) => {
          console.log("操作异常！", error);
          this.editOrderPopupData.visible = false;
        });
    },
    /* ----------------退款 ---------------- */
    refund() {
      let wid = this.wid;
      let money = this.money;
      let moneyNew = parseFloat(this.moneyNew);
      if (wid == null || wid == "" || wid == undefined) {
        this.$message.warn("wid参数不能为空！");
        return;
      }
      if (
        moneyNew == null ||
        moneyNew == "" ||
        moneyNew == undefined ||
        moneyNew == "0" ||
        moneyNew == 0
      ) {
        this.$message.warn("退款金额不为为0或空！");
        return;
      }
      if (moneyNew > money) {
        this.$message.warn("退款金额不能超过订单金额！");
        return;
      }
      if (
        this.orderTime == null ||
        this.orderTime == "" ||
        money == undefined
      ) {
        this.$message.warn("订单时间为空，数据异常！");
        return;
      }
      refundParam.wid = wid;
      refundParam.money = moneyNew * 100;
      refundParam.remark = this.remark;
      refundParam.userId = this.customerUserId;
      if( this.updatePay=='余额'){
        refundParam.payType = 5;
      }else if(this.updatePay=='支付宝'){
        refundParam.payType = 2;
      }else if(this.updatePay=='微信'){
        refundParam.payType = 3;
      }else if(this.updatePay=='移动支付'){
        refundParam.payType = 4;
      }else if(this.updatePay=='余额和在线'){
        refundParam.payType = 6;
      }else{
        //现金支付
        refundParam.payType = 1;
      }
      let type = 2;
      if (
        new Date().getFullYear() == new Date(this.orderTime).getFullYear() &&
        new Date().getMonth() == new Date(this.orderTime).getMonth() &&
        new Date().getDay() == new Date(this.orderTime).getDay()
      ){
        type = 1;
      }
      refundParam.type = type;
      //0:订单 1:活动 2:包月
      refundParam.sourceType=0;
      this.refundPopupData.loading = true;
      ParkingRecordApi.channelRefund(refundParam)
        .then((data) => {
          let code = data.code;
          if (code === 2000) {
            this.$message.success("操作成功！");
            this.hideRefundPopupData();
            this.queryData();
          } else {
            this.$message.error("操作失败！" + data.data);
          }
        })
        .catch((error) => {
          this.$message.error("操作失败！" + error.data);
        });
    },

    /* ---------------- 查询 ---------------- */
    queryData() {
      let condition = this.getQueryCondition();
      this.loading && this.loading.close(); // 这里是为了防止还没有请求结束（loading未关闭）再次连续触发
      this.loading = Loading.service({
        // 这里可以直接使用选择器名称，当然也可以用ref获取DOM结构，可以提前把DOM结构缓存起来，这样频繁被触发的时候是不是就不会重新获取DOM了呢？好像可以提升一丢丢性能吧（个人理解）
        target: ".content",
      });
      ParkingRecordApi.getChargeDatil(condition)
        .then((data) => {
          let { list, total, pageNum, pageSize } = data.data.info;
          let array = list || [];
          array = array.map((item, index) => {
            return { ...item, no: total - (pageNum - 1) * pageSize - index };
          });
          for (var i in array) {
            if (
              array[i].endTime == null ||
              array[i].endTime == "" ||
              array[i].endTime == undefined
            ) {
              var timeD = this.getTimeDifference(
                array[i].startTime,
                this.nowTime()
              );
              array[i].sumTime = timeD;
            }
          }
          this.dataSource = array;
          this.pagination.total = total;
          this.pagination.current = pageNum;
          this.should = data.data.should;
          this.reality = data.data.reality;
          this.favorableAmount = data.data.favorableAmount;
          this.loading.close();
        })
        .catch((error) => {
          console.log("获取停车记录数据异常！", error);
        });
    },
    nowTime() {
      let yy = new Date().getFullYear();
      var mm =
        new Date().getMonth() < 10
          ? "0" + (new Date().getMonth() + 1)
          : new Date().getMonth() + 1;
      var dd =
        new Date().getDate() < 10
          ? "0" + new Date().getDate()
          : new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      return yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
    },
    getTimeDifference(startTime, endTime) {
      // let timeData={}
      var timeStr = "";
      if (startTime != null) {
        let sd = startTime.substring(0, 19).replace(/-/g, "/"); // 将时间字符串截取到秒，并将其中的-换成/
        let se = ""; // 这是定义结束时间，如果为空，就获取当前时间
        let cdate = new Date();
        if (endTime != null || endTime != "") {
          se = endTime.substring(0, 19).replace(/-/g, "/"); // 将时间字符串截取到秒，并将其中的-换成/
        } else {
          se = cdate.getTime();
        }
        let sde = new Date(se).getTime() - new Date(sd).getTime(); // 将时间字符转成时间戳
        if (sde > 1) {
          // 当有差值时，就计算
          // let a = (sde/1000 + '').split('.') // 这是获取ms
          // if(a.length>1){
          //     // timeData['ms'] = Math.floor(Number('0.'+a[1]*1000))
          //     if(Math.floor(Number('0.'+a[1]*1000)) >0){
          //         timeStr=timeStr+Math.floor(Number('0.'+a[1]*1000))+"秒"
          //     }
          // }
          // debugger
          let d = (sde / 1000 / 60 / 60 / 24 + "").split("."); // 这是获取h d
          if (Number(d[0]) != null && Number(d[0]) != "") {
            timeStr = timeStr + Number(d[0]) + "天";
          }
          // timeData['d'] = Number(d[0])  // 这是获取d
          if (d.length > 1) {
            // timeData['h'] = Math.floor(Number('0.'+d[1])*24)
            if (Math.floor(Number("0." + d[1]) * 24) > 0) {
              timeStr = timeStr + Math.floor(Number("0." + d[1]) * 24) + "小时";
            }
          }
          let c = (sde / 1000 / 60 / 60 + "").split("."); // 这是获取min
          if (c.length > 1) {
            // timeData['min'] = Math.floor(Number('0.'+c[1])*60)
            if (Math.floor(Number("0." + c[1]) * 60) > 0) {
              timeStr = timeStr + Math.floor(Number("0." + c[1]) * 60) + "分";
            }
          }
          let b = (sde / 1000 / 60 + "").split("."); // 这是获取s
          if (b.length > 1) {
            // timeData['s'] = Math.floor(Number('0.'+b[1])*60)
            if (Math.floor(Number("0." + b[1]) * 60) > 0) {
              timeStr = timeStr + Math.floor(Number("0." + b[1]) * 60) + "秒";
            }
          }
        }
      }
      return timeStr;
    },

    /* ---------------- 表格 ---------------- */
    customRow(record) {
      return {
        on: {
          // 事件
          click: () => {
            this.currRowData = record;
            this.tableState.rowId = record.id;
          }, // 点击行
          dblclick: () => {
            this.showCorrectionPopup(record);
          },
        },
      };
    },

    setRowClassName(record) {
      return record.id === this.tableState.rowId ? "clickRowStyl" : "";
    },

    /* ---------------- 表单功能 ---------------- */
    exportExcel() {
      let condition = this.getQueryCondition();
      ParkingRecordApi.exportChargeExcel(condition)
        .then((res) => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel",
          });
          link.href = URL.createObjectURL(blob);
          var fileName = decodeURIComponent(res.headers.filename);
          if (fileName == null || fileName == "undefined") {
            fileName = "缴费详情.xlsx";
          }
          link.style.display = "none";

          link.setAttribute("download", `${fileName}`);
          link.click();
          // document.body.removeChild(link) // 下载完成移除元素
          // window.URL.revokeObjectURL(link.href)
        })
        .catch((err) => {
          console.log("error");
          console.log(err);
          let data = err.data;
          if (data) {
            return this.$message.warn(data);
          }
        });
    },

    /* ---------------- 标题展开 ---------------- */
    switchExpend() {
      this.isExpand = !this.isExpand;
    },

    /* ---------------- 车牌纠正弹窗 ---------------- */
    showCorrectionPopup(item) {
      let { comeInUrl, getOutUrl, id } = item;
      this.correctPopupData.visible = true;
      let imageList = [];
      if (comeInUrl) {
        let array = comeInUrl.split(",").map((item) => {
          if (item != "none") {
            return item;
          }
        });
        imageList.push(...array);
      }
      if (getOutUrl) {
        let array = getOutUrl.split(",").map((item) => {
          if (item != "none") {
            return item;
          }
        });
        imageList.push(...array);
      }
      this.correctPopupData.imageList = imageList;
      this.correctPopupData.loading = false;
      this.correctPopupData.id = id;
    },

    hideCorrectionPopup() {
      this.correctPopupData.visible = false;
    },

    commitCorrect() {
      this.hideCorrectionPopup();
    },

    cancelCorrect() {
      this.hideCorrectionPopup();
    },
    onChangeTime(data, dataStrng) {
      this.addOrder.orderTime = dataStrng;
    },
    handleOk() {
      ParkingRecordApi.insertWalletRecord(this.addOrder)
        .then((res) => {
          this.$message.success(res.msg);
        })
        .catch((err) => {
          console.log(err);
        });
      this.closeAddModle();
    },
    handleCancel() {
      this.closeAddModle();
    },
    closeAddModle() {
      this.queryData();
      for (const key in this.addOrder) {
        this.addOrder[key] = "";
      }
      this.visible = false;
    },
  },

  /*计算层*/
  computed: {
    computedStyle() {
      return function (selectId) {
        return this.selectId == selectId ? "" : "";
      };
    },

    expendStyle() {
      return this.isExpand ? "" : "height: 150px; overflow: hidden;";
    },
    computedDue() {
      let dataSource = this.dataSource || [];
      let result = 0;
      dataSource.forEach((item) => {
        result += isNaN(parseInt(item.shouldMoney))
          ? 0
          : parseInt(item.shouldMoney);
      });
      return result / 100;
    },
    computedDueR() {
      let dataSource = this.dataSource || [];
      let result = 0;
      dataSource.forEach((item) => {
        result += isNaN(parseInt(item.realityMoney))
          ? 0
          : parseInt(item.realityMoney);
      });
      return result / 100;
    },
    computedDueF() {
      let dataSource = this.dataSource || [];
      let result = 0;
      dataSource.forEach((item) => {
        result += isNaN(parseInt(item.favorableAmount))
          ? 0
          : parseInt(item.favorableAmount);
      });
      return result / 100;
    },
  },
  /*渲染层*/
  mounted() {
    this.button_time(0);
    this.initParkList();
    //当月或跨月订单切换
    //this.orderTypeTableSwtch(0);
  },
};
</script>

<style scoped>
.content {
  width: 100%;
  height: 100%;
}

.header-setting {
  position: relative;
  width: 100%;
  height: auto;
  background: #fff;
  padding-bottom: 40px;
}

.header-setting .breadcrumb {
  margin-left: 41px;
  padding-top: 15px;
}

/* 展开 */
.box-expand {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  /* text */
  cursor: pointer;
  line-height: 40px;
  font-size: 15px;
  text-align: center;
  color: #020202;
  background: white;
}

/*表格行选中背景颜色*/
.clickRowStyl {
  background-color: #c1e0fd;
}

.box-condition-body {
  padding-top: 15px;
}

.box-condition-item {
  display: flex;
  align-items: center;
  min-width: 1500px;
  padding: 10px 0;
}

.box-condition-item .box-item {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 5px 5px 20px 5px;
}

.button_time button {
  margin-left: 10px;
}

/* 表单 */
.box-form {
  padding-left: 40px;
  padding-right: 40px;
  min-height: 705px;
  background: #fff;
  margin-top: 8px;
}

.box-form .box-tool {
  padding-top: 11px;
  margin: 8px 0;
  width: 100%; /* flex */
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* box-correction-popup */
.box-correction-popup {
  padding: 20px;
  height: 555px;
  /* flex */
  display: flex;
  align-items: center;
}

.box-correction-popup .box-image {
  padding: 0 15px;
  width: 888px;
  height: 500px;
}

.box-correction-popup .box-image .icon-image {
  width: 100%;
  height: 100%;
}

.box-correction-popup .box-correct {
  margin: 0 15px;
  width: 310px;
  height: 500px;
}

.box-correction-popup .box-correct .item-correct {
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.box-correction-popup .box-correct .item-correct .text-correct {
  font-weight: 300;
  font-size: 14px;
  width: 100px;
}

.box-correction-popup .box-correct .item-correct .text-value {
  font-weight: 300;
  font-size: 14px;
  line-height: 1.428571429;
  color: #020202;
}
</style>
